<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh 
          v-model="isRefreshLoading" 
          :success-text="refreshSuccessText"
          :success-duration="1500"
          @refresh="onRefresh">

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- 文章内容具体展示 -->
        <article-item v-for="(article, index) in articles" :key="index" :article="article">
          
        </article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import {getArticles} from '@/api/article'
import ArticleItem from '@/components/article-item'
import {debounce} from 'lodash'

export default {
  props:{
    channel:{
      type:Object,
      required:true,
    }
  },
  components:{
    ArticleItem
  },
  data() {
    return {
      articles: [],
      loading: false,
      finished: false,
      refreshing: false,
      timestamp:null,
      isRefreshLoading:false,
      refreshSuccessText:'',
      scrollTop:0
    };
  },
  methods: {
    async onLoad() {
      const {data} = await getArticles({
        channel_id:this.channel.id,
        timestamp:this.timestamp || Date.now(),
        with_top:1
      })
      const {results} = data.data
      this.articles.push(...results) // results是一个数组，不能在数组里push数组，用...运算符扩展
      this.loading = false //加载下一页数据
      if (results.length) { //如果还有数据就更新时间戳，加载下一页数据
        this.timestamp = data.data.pre_timestamp
      }else{ //没有数据直接 取消加载
        this.finished = true
      }
    },
    async onRefresh() {
      // 清空列表数据
      const {data} =await getArticles({
        channel_id:this.channel.id,
        timestamp:Date.now(),
        with_top:1
      })
      const {results} = data.data
      this.articles.unshift(...results)
      this.isRefreshLoading = false
      this.refreshSuccessText = `更新了${results.length}条数据`
    },
  },
  mounted() {
    const articleList =  this.$refs['article-list']
    articleList.onscroll =debounce(() =>{
      this.scrollTop = articleList.scrollTop
    }, 50)
  },
  activated() {
    this.$refs['article-list'].scrollTop = this.scrollTop
  },
}
</script>

<style lang="less" scoped>
.article-list{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 90px;
  overflow-y:auto;
}
</style>